﻿using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Tippelde.Entities;
using Tippelde.Services.Dtos;

namespace Tippelde.Services.Teams
{
    public class TeamManager : ITeamManager
    {
        private readonly Expression<Func<Team, TeamHeaderData>> TeamHeaderSelector =
            t => new TeamHeaderData
            {
                Id = t.Id,
                Name = t.Name,
                ShortName = t.ShortName,
                LogoUrl = t.LogoUrl,
                IsNational = t.IsNational
            };


        public Team CreateTeam(TeamHeaderData teamHeader)
        {
            using (var ctx = new TippeldeEntities())
            {
                Team t = new Team
                {
                    Name = teamHeader.Name,
                    ShortName = teamHeader.ShortName,
                    Description = teamHeader.Description,
                    LogoUrl = teamHeader.LogoUrl,
                    IsNational = teamHeader.IsNational
                };
                ctx.Teams.Add(t);
                ctx.SaveChanges();
                return t;
            }
        }

        public IPagedList<TeamHeaderData> GetAllTeamHeaders(int? page)
        {
            using (var ctx = new TippeldeEntities())
            {
                return ctx.Teams.OrderBy(t => t.Name).OrderByDescending(t => t.IsNational).Select(TeamHeaderSelector).ToPagedList(page ?? 1, 25);
            }
        }

        public List<TeamHeaderData> GetAllTeamHeadersStartsWith(string begin)
        {
            using (var ctx = new TippeldeEntities())
            {
                return ctx.Teams.Where(t => (t.Name.StartsWith(begin) || t.ShortName.StartsWith(begin))).OrderBy(t => t.Name).Select(TeamHeaderSelector).ToList();
            }
        }


        public TeamHeaderData GetTeamHeader(int id)
        {
            using (var ctx = new TippeldeEntities())
            {
                return ctx.Teams.Where(t => t.Id == id).Select(TeamHeaderSelector).SingleOrDefault();
            }
        }

        public Team EditTeam(TeamHeaderData teamHeader)
        {
            using (var ctx = new TippeldeEntities())
            {
                Team team = ctx.Teams.SingleOrDefault(t => t.Id == teamHeader.Id);
                if (team != null)
                {
                    team.Name = teamHeader.Name;
                    team.ShortName = teamHeader.ShortName;
                    team.Description = teamHeader.Description;
                    team.LogoUrl = teamHeader.LogoUrl;
                    team.IsNational = teamHeader.IsNational;
                }
                ctx.SaveChanges();
                return team;
            }
        }
    }
}
